<?php
/**
 * 2020/9/30
 * Created by breeze
 * User: breeze
 */
declare(strict_types=1);
namespace app\common\lib\sms;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use app\common\lib\sms\SmsBase;
use think\facade\Log;
class AliSms implements SmsBase
{
    /**
     * 阿里云发送短信接口
     * @param string $phone //电话号码
     * @param int $code
     * @return bool
     * @throws ClientException
     */
    public static function sendCode(string $phone, int $code) :bool {
        if(empty($phone) || empty($code)){
            return false;
        }
        AlibabaCloud::accessKeyClient(config("aliyun.access_key_id"), config("aliyun.access_secret"))
            ->regionId(config("aliyun.RegionId"))
            ->asDefaultClient();
        $templateParam = [
            "code" => $code
        ];

        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host(config("aliyun.host"))
                ->options([
                    'query' => [
                        'RegionId' => config("aliyun.RegionId"),
                        'PhoneNumbers' => $phone,
                        'SignName' => config("aliyun.SignName"),
                        'TemplateCode' => config("aliyun.TemplateCode"),
                        'TemplateParam' => json_encode($templateParam),
                    ],
                ])
                ->request();
            Log::info("alisms_sendCode_result".json_encode($result->toArray()));
            print_r($result->toArray());
        } catch (ClientException $e) {
            Log::error("alisms_sendCode_ClientException".$e->getErrorMessage());
            return false;
//            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            Log::error("alisms_sendCode_ServerException".$e->getErrorMessage());
            return false;
//            echo $e->getErrorMessage() . PHP_EOL;
        }
        return true;
    }
}